package com.example.im.mvp.presenter

import android.content.Context
import android.widget.EditText
import com.example.im.common.ImApplication
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.ISearchView
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class SearchPresenter(mContext: Context, mView: ISearchView?) :
    BasePresenter<ISearchView>(mContext, mView) {

    fun searchVague(edit: EditText) {
        val observable = RxTextView.textChanges(edit)
            .skip(1).debounce(100, TimeUnit.MILLISECONDS)
            .map { it.toString() }
            .subscribeOn(Schedulers.io())
            .flatMap {
                val friendOrRoom = if (it.isNotEmpty())
                    ImApplication.appDatabase().friendOrRoomDao()
                        .selectFriendOrRoomBySearch(it) ?: mutableListOf<FriendOrRoom>()
                else mutableListOf<FriendOrRoom>()
                Observable.just(friendOrRoom)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                val friends = mutableListOf<FriendOrRoom>()
                val rooms = mutableListOf<FriendOrRoom>()
                it.forEach { friendOrRoom ->
                    if (friendOrRoom.type == 1) {
                        friends.add(friendOrRoom)
                    } else {
                        rooms.add(friendOrRoom)
                    }
                }
                getView().onSearchFriendGood(friends)
                getView().onSearchGroupRoom(rooms)

            }, {
                getView().onHint("搜索错误")
            })
        this.disposable.add(observable)
    }

}